(function() {

	var appModule = angular.module('tracecashModule');
	
	appModule.directive('requiredDocumentationList', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/documentation/required-documentation-list.html',
			require : '^ngModel',
			scope : {
				sinister : '=ngModel',
				config : "="
			}
		};
	});

	appModule.directive('requiredDocumentationPersonList', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/documentation/required-documentation-person-list.html',
			controller: 'RequiredDocumentationPersonListCtrl',
			require : '^ngModel',
			scope : {
				requiredDocumentationList : '=ngModel',
				target : '=',
				sinisterId : "=",
				config : "="
			}
		};
	});
	
	appModule.controller('RequiredDocumentationPersonListCtrl', ['$scope', '$rootScope', '$routeParams', '$http', '$modal', '$filter', function($scope, $rootScope, $routeParams, $http, $modal, $filter) {
		$scope.letter = function() {
			$scope.isLoading = true;
			$http.get($rootScope.REST_PATH + '/letter/generateDeclaration/' + $scope.sinisterId + '/0').success(function(data) {
				if (data.code == $rootScope.CODE_SUCCESS) {
					$scope.message = data;
				}
				$scope.isLoading = false;
			});
		};
		$scope.add = function(target) {
			$scope.open({"status" : "REQUIRED", "target" : {"id" : target.id, "entityType" : target.entityType}}, true);
		};
		$scope.edit= function(document) {
			$scope.open(document);
		};
		$scope.remove= function(index) {
			$scope.requiredDocumentationList.splice(index, 1);
		};
		$scope.getSinisterRequiredDocumentDates = function(id) {
			$http.get($rootScope.REST_PATH + '/letter/getSinisterRequiredDocumentDates/' + id).success(function(dates) {
				$scope.sinisterRequiredDocumentDates = '';
				for(var i = 0; i < dates.length; i++) {
					$scope.sinisterRequiredDocumentDates += $filter('date')(dates[i], "dd/MM/yyyy");
					$scope.sinisterRequiredDocumentDates += ' ';
				}
			});
		};
		$scope.open = function(document, isNew) {
			var modalInstance = $modal.open({
				templateUrl : 'html/documentation/required-documentation-detail.html',
				controller : 'RequiredDocumentationDetailCtrl',
				size: 'lg',
				resolve: {
					document: function () {
			        	return document;
				    }
			     }
			});
			modalInstance.result.then(function (data) {
				if (isNew) {
					$scope.requiredDocumentationList.push(document);
				}
		    }, function () {
		    });
		};
	}]);

	appModule.controller('RequiredDocumentationDetailCtrl', ['$scope', '$rootScope', '$http', '$modalInstance', 'document', function($scope, $rootScope, $http, $modalInstance, document) {
		$scope.document = document;
		$scope.save = function() {
			$modalInstance.close(document);
		};
		$scope.cancel = function() {
			$modalInstance.dismiss('cancel');
		};
	}]);

})();